package cn.rubintry.bug.hunting.decoration;

import android.content.res.Resources;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    // 定义间距值，注意这个值应为dp单位
    private final int verticalSpaceHeight;

    private int total;

    public VerticalSpaceItemDecoration(int verticalSpaceHeight, int total) {
        this.verticalSpaceHeight = px2dp(verticalSpaceHeight);
        this.total = total;
    }

    // 将dp转为px
    public static int px2dp(float dpValue) {
        float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        // 添加垂直间距
        outRect.bottom = verticalSpaceHeight; // 在每个item底部添加间距
        if (parent.getChildAdapterPosition(view) == 0) { // 对于首个item不添加上边距，以免与顶部有双倍间距
            outRect.top = verticalSpaceHeight + px2dp(10);
            outRect.bottom = verticalSpaceHeight;
        } else if(parent.getChildAdapterPosition(view) == total - 1){
            outRect.bottom = verticalSpaceHeight + px2dp(10);
        } else {
            outRect.bottom = verticalSpaceHeight; // 在非首个item的顶部添加间距
        }
//        outRect.top = verticalSpaceHeight;
    }
}
